#!/bin/sh

NEWSID=$1
ORIGSID=$2

if [ -z "$NEWSID" ]; then
   echo "need NEW SID name to proceed"
   exit 1
fi

if [ -z "$ORIGSID" ]; then
   echo "need ORIG SID name to proceed"
   exit 1
fi
cp $ORACLE_HOME/dbs/init$ORIGSID.ora $ORACLE_HOME/dbs/init$NEWSID.ora
export ORACLE_SID=$ORIGSID

$ORACLE_HOME/bin/sqlplus / as sysdba << EOF
set heading off
set feedback off
startup mount;
exit;
EOF

orafile=$ORACLE_HOME/dbs/init$NEWSID.ora
temporafile=$ORACLE_HOME/dbs/init$NEWSID_temp.ora

sed '/db_name=/d' $orafile > $temporafile
mv $temporafile $orafile
sed '/log_archive_format=/d' $orafile > $temporafile
mv $temporafile $orafile
sed '/.__/d' $orafile > $temporafile
mv $temporafile  $orafile
echo "*.db_name=$NEWSID" >> $orafile
echo "*.log_archive_format='arc_S-%s_T-%t_A-%r'" >> $orafile

#sed -i "s/$ORIGSID/$NEWSID/g" $ORACLE_HOME/dbs/init$NEWSID.ora

set +x
username="sys"
pssword="change_on_install"
if [ ! -z "$ouser" ]; then
   username=$ouser
fi
if [ ! -z "$opass" ]; then
   pssword=$opass
fi

if [ "$nonid" != "true" ]; then
$ORACLE_HOME/bin/nid TARGET=$username/$pssword DBNAME=$NEWSID LOGFILE=newsidlog.log
fi

#recomment?
#export ORACLE_SID=$NEWSID
#$ORACLE_HOME/bin/sqlplus / as sysdba << EOF1
#set heading off
#set feedback off
#shutdown immediate;
#exit;
#EOF1

rm -f $ORACLE_HOME/dbs/init$ORIGSID.ora
rm -f $ORACLE_HOME/dbs/spfile$ORIGSID.ora
rm -f $ORACLE_HOME/dbs/orapw$ORIGSID

# orapwd file=$ORACLE_HOME/dbs/orapw$NEWSID password=change_on_install ignorecase=yes
# cp orapworigsid orapwnewsid

export ORACLE_SID=$NEWSID

$ORACLE_HOME/bin/sqlplus / as sysdba << EOF2
set heading off
set feedback off
startup nomount pfile='$ORACLE_HOME/dbs/init$NEWSID.ora';
create spfile='$ORACLE_HOME/dbs/spfile$NEWSID.ora' from pfile='$ORACLE_HOME/dbs/init$NEWSID.ora';
shutdown immediate;
exit;
EOF2


$ORACLE_HOME/bin/sqlplus / as sysdba << EOF2
set heading off
set feedback off
startup mount;
alter database open resetlogs;
exit;
EOF2

#$ORACLE_HOME/bin/sqlplus / as sysdba @verifyDatabase.sql

exit 0
